/*
 * Copyright (C) 2013 TinhVan Outsourcing.
 */
package com.getinstaliker.util.network.httptask;

import java.lang.ref.WeakReference;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.view.WindowManager;

import com.getinstaliker.util.network.util.AndroidVersionUtils;

/**
 * The Class BaseTask.
 *
 * @author HuanND
 * @param <Params> the generic type
 * @param <Progress> the generic type
 * @param <Result> the generic type
 */
public abstract class BaseTask<Params, Progress, Result> extends AsyncTask<Params, Progress, Result> {
    
    /** The m dialog. */
    protected ProgressDialog mDialog;
    
    /** The m context. */
    protected WeakReference<Context> mContext = new WeakReference<Context>(null);
    
    /** The is show loading. */
    private boolean isShowLoading = true;

    /**
     * Instantiates a new base task.
     *
     * @param pContext the context
     * @param pShowLoading the show loading
     */
    public BaseTask(Context pContext, boolean pShowLoading) {
        this.mContext = new WeakReference<Context>(pContext);
        this.isShowLoading = pShowLoading;
    }

    /* (non-Javadoc)
     * @see android.os.AsyncTask#onPreExecute()
     */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        if (isShowLoading) {
            mDialog = new ProgressDialog(mContext.get());
            mDialog.setMessage("Loading...");
            mDialog.setCancelable(false);
            try {
                mDialog.show();
            } catch (WindowManager.BadTokenException e) {} catch (Exception e) {}
        }
    }

    /* (non-Javadoc)
     * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
     */
    @Override
    protected void onPostExecute(Result result) {
        super.onPostExecute(result);
        try {
            if (isShowLoading && mDialog != null && mDialog.isShowing()) {
                mDialog.dismiss();
                mDialog = null;
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

    /**
     * Run.
     *
     * @param params the params
     */
    public void run(Params... params) {
        this.running(params);
    }

    /**
     * Running.
     *
     * @param params the params
     */
    private void running(Params... params) {
        if (AndroidVersionUtils.isBeforeHoneycomb()) {
            this.execute(params);
        } else {
            this.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
        }
    }
    
}
